package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author moningxi
 */
@Component
@Slf4j
public class OrderStatusTask {
    @Resource
    private OrderMapper orderMapper;

    /**
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void autoCancel() {
        // 查询超时未支付订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime orderTime = now.plusMinutes(-15);
        List<Orders> ordersList = orderMapper.listByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, orderTime);

        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("系统自动取消");
            orders.setCancelTime(now);
        }

        // 批量取消订单
        if (!ordersList.isEmpty()) {
            log.info("系统自动取消订单：{}", ordersList);
            orderMapper.updateBatch(ordersList);
        }
    }

    /**
     * 每天凌晨一点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void autoComplete() {
        // 查询昨日派送中的订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime orderTime = now.plusMinutes(-60);
        List<Orders> ordersList = orderMapper.listByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, orderTime);
        ordersList.forEach(e -> e.setStatus(Orders.COMPLETED));

        // 批量完成订单
        if (!ordersList.isEmpty()) {
            log.info("系统自动完成订单：{}", ordersList);
            orderMapper.updateBatch(ordersList);
        }
    }
}
